var API = require('API');
var popup = ''
    + '';
module.exports = ['$timeout', function ($timeout) {
    return {
        restrict: 'E',
        scope   : {
            shop    : "="
        },
        require: "ngModel",

        template: '<div class="picker-content"> \
                        <div class="picker-input"> \
                            <input type="text" class="display" \
                                ng-show="!show" value="{{name}}" > \
                            <input type="text" class="input" \
                            ng-show="show" \
                            type="text" ng-model="picker_filter.name" > \
                        </div> \
                        <div class="picker-menu" ng-show="show"> \
                            <div class="picker-item truncate-item " ng-click="truncate()">[X]</div> \
                            <div class="picker-item" \
                                ng-repeat="evaluator in data|orderBy:[\'name\'] | filter:picker_filter" \
                                ng-click=\'$event.stopPropagation();submit(evaluator)\'>\
                                {{evaluator.name}}\
                                </div> \
                        </div> \
                    </div>',

        replace   : true,

        link: function($scope, element, attrs, ngModel){

            $scope.data = [];
            $scope.show = false;
            $scope.picker_filter = {};

            ngModel.$render = function(){
                $scope.name = ngModel.$viewValue && ngModel.$viewValue.name || "";
            };

            var $element = $(element);

            var $overlay = $('<div/>').css({
                height    : '100%',
                width     : '100%',
                position  : 'fixed',
                top       : 0,
                left      : 0,
                background: "rgba(255,255,255,0.0)",
                "z-index" : "1"
            }).click(function () {
                $scope.$apply(function () {
                    $scope.show = false;
                    $overlay.detach();
                });
            });

            var close_menu = function () {
                $scope.show = false;
                $overlay.detach();
            };

            var items = [];
            $scope.selected = -1;
            var reset_items = function () {
                $scope.selected = -1;
                items = $element.find('.picker-item').hover(function () {
                    items.removeClass('selected');
                    $(this).addClass('selected');
                }, function () {
                    $(this).removeClass('selected');
                });
            };
            var $input = $element.find('input.input');
            var $menu = $element.find('.picker-menu');
            var $display = $element.find('input.display');

            var i = 0;
            $input.keydown(function (e) {
                var keyCode = e.keyCode;

                if (keyCode == 38) { // down
                    $(items).removeClass('selected');
                    if ($scope.selected !== -1) {
                        $scope.selected--;
                    }
                    if ($scope.selected == -1) {
                        //clear all the style
                    } else {
                        $(items[$scope.selected]).addClass('selected');
                    }
                    if (i <= 30) {
                        i = 0;
                        $menu.scrollTop(i);
                    } else {
                        i = i - 30;
                        $menu.scrollTop(i);
                    }
                }
                else if (keyCode == 40) {//up
                    if ($scope.selected < items.length - 1) {
                        $scope.selected++;
                    }
                    $(items).removeClass('selected');
                    $(items[$scope.selected]).addClass('selected');

                    if ($scope.selected >= 3) {
                        if (i >= $(items).length * 30 - 120) {
                            $menu.scrollTop(i);
                        } else {
                            $menu.scrollTop(i);
                            i = i + 30;
                        }
                    }
                }
                else if (keyCode == 13) {
                    //enter
                    if ($scope.selected > -1) {
                        $(items[$scope.selected]).trigger('click')
                    }
                    else {
                        //close the menu and leave the same
                        $scope.$apply(function () {
                            close_menu();
                        })
                    }
                }
                else if (keyCode == 27) {
                    $scope.$apply(function () {
                        close_menu();
                    })
                }
                else {
                    $scope.$apply(function () {
                        $timeout(function () {
                            reset_items();
                        });
                    });
                }
            });

            function get_shop_id() {
                var shop_id = $scope.shop ? $scope.shop.id : null;
                // console.log('shop.id', shop_id);
                return shop_id;
            }

            API.user.evaluator(get_shop_id(), function (list) {
                $scope.data = list;
            });

            $scope.$watch('shop', function (val, old) {
                if (val !== undefined && val !== old) {
                    API.user.evaluator(get_shop_id(), function (list) {
                        $scope.data = list;
                    });
                }
            });

            $display.focus(function () {
                $scope.$apply(function () {
                    $scope.show = true;
                    $overlay.appendTo($element.find('.picker-input'));
                    $timeout(function () {
                        reset_items();
                        $input[0].focus();
                    });
                });
            });

            $scope.submit = function (user) {
                ngModel.$setViewValue(user);
                ngModel.$render();
                close_menu();
            };

            $scope.truncate = function () {
                ngModel.$setViewValue(null);
                ngModel.$render();
                close_menu();
            };
        }

    }
}];
